import { defineStore } from 'pinia'
import { store } from '../index'
import { useCache } from '@/hooks/web/useCache'
import { getOpenIdKey } from '@/utils'

const { wsCache } = useCache()

interface AppState {
  tabbarIndex: number
  mobile: string
  appId: string
  openid: string
  last_name: string
  guest_title: string
  hotel_name: string
  images: string[]
  my_image: string
}

export const useAppStore = defineStore('app', {
  state: (): AppState => {
    return {
      tabbarIndex: 0, // 默认首页
      mobile: 'undefined',
      appId: '',
      openid: '',
      hotel_name: '',
      last_name: '',
      guest_title: '',
      images: [],
      my_image: ''
    }
  },
  getters: {
    getTabbarIndex(): number {
      return this.tabbarIndex
    },
    getMobile(): string {
      return this.mobile
    },
    getSecretMobile(): string {
      if (this.mobile === 'undefined' || !this.mobile) {
        return ''
      }
      const maskLength = Math.ceil(this.mobile.length / 3)
      const mLength = this.mobile.length

      return [this.mobile.substring(0, mLength - 2 * maskLength), new Array(maskLength).fill('*').join(''), this.mobile.substring(mLength - maskLength, mLength)].join('')
    },
    getAppId(): string {
      return this.appId
    },
    getOpenId(): string {
      return this.openid
    },
    getHotelName(): string {
      return this.hotel_name
    },
    getLastName(): string {
      return this.last_name
    },
    getGuestTitle(): string {
      return this.guest_title
    },
    getImages(): string[] {
      return this.images
    },
    getMyImage(): string {
      return this.my_image
    },
  },
  actions: {
    setTabbarIndex(tabbarIndex: number) {
      this.tabbarIndex = tabbarIndex
    },
    setMobile(mobile: string) {
      this.mobile = mobile
    },
    setAppId(appid: string) {
      this.appId = appid
    },
    setOpenId(openid: string) {
      this.openid = openid
      wsCache.set(getOpenIdKey(), openid)
    },
    setHotelName(hotel_name: string) {
      this.hotel_name = hotel_name
    },
    setGuestTitle(guest_title: string) {
      this.guest_title = guest_title
    },
    setLastName(last_name: string) {
      this.last_name = last_name
    },
    setImages(images: string[]) {
      this.images = images
    },
    setMyImage(my_image: string) {
      this.my_image = my_image
    },
  }
})

export const useAppStoreWithOut = () => {
  return useAppStore(store)
}
